package com.servlet.form;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.listener.ContextListener;
import com.servlet.mail.SendMail;
import com.servlet.model.database.BaseAcces;
import com.servlet.security.MD5;

public class SendPasswdForm extends HttpServlet
{
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		boolean correct = false;
		
		HttpSession session = request.getSession();
		//BaseAcces base = (BaseAcces) this.config.getServletContext().getAttribute("base");
		
		BaseAcces base = ContextListener.base;

		String email = request.getParameter("email");
		
		String resultat = null;
		
		if( email != null && email != "" )
		{
			if( Format.verifyEmail(email) )
			{
				if( base.existEmail(email) )
				{
					correct = true;
				}
				else
				{
					resultat = "il n'existe aucun compte avec cet email";
				}
			}
			else
			{
				resultat = "email erroné";
			}
		}
		else
		{
			resultat = "vous devez entrer votre email";
		}
		
		if( correct )
		{
			HashMap<String,String> names = base.getPasswdName(email);
			if(names != null)
			{
				String oldPasswd = names.get("passwd");
				String first_name = names.get("first_name");
				String last_name = names.get("last_name");
				//System.out.println(oldPasswd);
				
				String newPasswd = SendMail.generatePasswd();
				//System.out.println(newPasswd);
				SendMail.send(email, first_name, last_name, newPasswd);
				
				newPasswd = MD5.generateCode(newPasswd);
				base.modifyPasswd(email, oldPasswd, newPasswd);
				
				session.setAttribute("resultat", "Un nouveau mot de passe vous a été envoyé");
				response.sendRedirect("login");
			}
			else
			{
				session.setAttribute("resultat", "L'envoi du mot de passe a échoué  ");
				
				response.sendRedirect("sendPasswd");
			}
		}
		else
		{
			System.out.println(resultat);
			
			session.setAttribute("resultat", "L'envoi du mot de passe a échoué : " + resultat );
			
			response.sendRedirect("sendPasswd");
		}
	}
}
